package org.howie.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import reactor.core.publisher.Mono;

@Slf4j
@Configuration
public class RedisRateLimiterConfig {

//    @Bean
//    public KeyResolver ipKeyResolver() {
//        return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getHostName());
//    }


//    @Bean(name="ipKeyResolver")
//    public KeyResolver userKeyResolver() {
//        return new KeyResolver() {
//            @Override
//            public Mono<String> resolve(ServerWebExchange exchange) {
//                //获取远程客户端IP
//                String hostName = exchange.getRequest().getRemoteAddress().getAddress().getHostAddress();
//                System.out.println("hostName:" + hostName);
//                return Mono.just(hostName);
//            }
//        };
//    }


    RedisRateLimiterConfig(){
        log.info("限流配置加载");
    }

    /**
     * 根据用户ip限流规则
     * @return
     */
    @Primary
    @Bean(value = "remoteAddrKeyResolver")
    public KeyResolver remoteAddrKeyResolver(){
        return exchange -> {
            String hostAddress=exchange.getRequest()
                    .getRemoteAddress()
                    .getAddress()
                    .getHostAddress();
            System.out.println(hostAddress);
            return Mono.just(hostAddress);
        };
    }
}
